//
//  SearchDetailViewController.m
//  Toyohu
//
//  Created by Heige on 16/4/14.
//  Copyright © 2016年 celia. All rights reserved.
//

#import "SearchDetailViewController.h"
#import "masonry.h"

#import "ReloadButton.h"
#import "ReloadButtonModel.h"

#import "LoginViewController.h"
#import "GPCustomSegment.h"
#import "MacroDefinition.h"

#import "MiddleTableViewCell.h"
#import "RightTableViewCell.h"
#import "TECustomTextField.h"
#import "GPAFNetworking3.h"
#import <MJRefresh.h>

#import "GPSearchBar.h"
#import "GPCustomMD.h"
#import <YYModel.h>

#import "knowledgeStyleOne.h"
#import "knowStyleTwoTableViewCell.h"
#import "LeftTableViewCell1.h"

#import "ExpertSearchModel.h"
#import "ExpertStyleOneTableViewCell.h"
#import "ExpertStyleTwoTableViewCell.h"
#import "UIViewController+ChangeStatus.h"

#import "NewsDetailViewController.h"

#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
@interface SearchDetailViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UITextField *searchTextField;
    
    UIScrollView *_bgScrollView;
    
    UITableView *_leftTableView;
    UITableView *_middleTableView;
    UITableView *_rightTableView;
    
    NSMutableArray *_leftArray;
    NSMutableArray *_middleArray;
    NSMutableArray *_rightArray;
    
    GPCustomSegment *_segment;
    
    NSMutableArray *idleImages;
    NSMutableArray *refreshingImages;
    
    NSMutableArray *knowledge;
    NSInteger knowledgePage;
    
    NSMutableArray *expert;
    NSInteger expertPage;
}

@end

@implementation SearchDetailViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_leftTableView.mj_header beginRefreshing];
    [_rightTableView.mj_header beginRefreshing];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    //数组初始化
    knowledgePage  = 1;
    knowledge = [NSMutableArray array];
    
    expertPage = 1;
    expert = [NSMutableArray array];
    //导航栏左边项
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.frame = CGRectMake(0, 0, 10, 15);
    [leftButton setBackgroundImage:[UIImage imageNamed:@"ARROW---LEFT@2x"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(goBackPreviousPage) forControlEvents:UIControlEventTouchDown];
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       
                                       target:nil action:nil];
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects: leftButtonItem,negativeSpacer, nil];
    

    _segment = [[GPCustomSegment alloc] initWithFrame:CGRectMake(0, 64, WIDTH, 50) imageArray:@[@"repository-gray@2x", @"community-gray@2x", @"say-gray@2x"] selectImageArray:@[@"repository",@"community",@"say"] titleArray:@[@"知识库",@"社区",@"专家有话说"] defaultSelectIndex:1 selectBlock:^(NSInteger selectIndex) {
        [_bgScrollView setContentOffset:CGPointMake(selectIndex * WIDTH, 0) animated:YES];
    } ];
    _segment.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_segment];

    
    UIView *MyView = [[UIView alloc]initWithFrame:CGRectMake(0, 114, WIDTH, 30)];
    MyView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    [self.view addSubview:MyView];
    
    UIView *yellowView = [[UIView alloc]initWithFrame:CGRectMake(10, 5, 3, 20)];
    yellowView.backgroundColor = [UIColor yellowColor];
    [MyView addSubview:yellowView];
    
    UILabel *countLabel = [[UILabel alloc]init];
    countLabel.text = @"全部（298）";
    countLabel.font = [UIFont systemFontOfSize:13];
    countLabel.textColor = [UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1];
    [MyView addSubview:countLabel];
    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(yellowView.mas_right).offset(10);
        make.centerY.equalTo(yellowView.mas_centerY);
        make.width.equalTo(@(120));
        make.height.equalTo(@(20));
    }];
    
    [self initView];
    
    [self initSearBar];
    [self changeNaviBar];

}

- (void)initSearBar
{
    
    GPSearchBar *searchBar = [[GPSearchBar alloc] initWithPlaceholder:@"搜索话题或专家" frame:CGRectMake(0, 0, 4*WIDTH/5, 35) search:^(NSString *str) {
        if (str.length > 0) {
            
            if (knowledge){
                [knowledge removeAllObjects];
                [_leftTableView reloadData];
            }
            [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?keyWord=%@&page=%ld&type=knowledge",Search,[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],knowledgePage] progress:^(NSProgress * _Nonnull progress) {
                
            } success:^(id  _Nonnull responseObject) {
                for (NSDictionary*myDict in responseObject[@"msg"]) {
                    knowledgeStyleOne*model = [[knowledgeStyleOne alloc]init];
                    [model yy_modelSetWithDictionary:myDict];
                    [knowledge addObject:model];
                    [_leftTableView.mj_footer endRefreshing];
                    [_leftTableView reloadData];
                
                }
                
            } failure:^(NSString * _Nonnull errorLD) {
                knowledgePage--;
            }];
    
            [searchBar.searchBar resignFirstResponder];
            
            if (expert) {
                [expert removeAllObjects];
                [_rightTableView reloadData];
            }
            [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?keyWord=%@&page=%ld&type=expert",Search,[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],expertPage] progress:^(NSProgress * _Nonnull progress) {
                
            } success:^(id  _Nonnull responseObject) {
                for (NSDictionary*myDict in responseObject[@"msg"]) {
                    ExpertSearchModel*model = [[ExpertSearchModel alloc]init];
                    [model yy_modelSetWithDictionary:myDict];
                    [expert addObject:model];
                    [_rightTableView.mj_footer endRefreshing];
                    [_rightTableView reloadData];
                    
                }
                
            } failure:^(NSString * _Nonnull errorLD) {
                expertPage--;
            }];

            
            
        }else{
            
        }
        
        
        
    }];
    searchBar.tag = 101;
    searchBar.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = searchBar;

}

- (void)initView
{
    idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=17; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%lu", (unsigned long)i]];
        [idleImages addObject:image];
    }
    
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 1111, 1111)];
    _bgScrollView.contentSize = CGSizeMake(WIDTH * 3, 0);
    _bgScrollView.bounces = NO;
    _bgScrollView.delegate = self;
    _bgScrollView.pagingEnabled = YES;
    _bgScrollView.showsHorizontalScrollIndicator = NO;
    _bgScrollView.showsVerticalScrollIndicator = NO;
    _bgScrollView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_bgScrollView];
    
    
    [_bgScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(146);
        make.bottom.equalTo(self.view).offset(0);
    }];
    

    _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -35, WIDTH, _bgScrollView.frame.size.height - 555) style:UITableViewStyleGrouped];
    _leftTableView.delegate = self;
    _leftTableView.backgroundColor = RGBA(235, 234, 229, 1);
    _leftTableView.dataSource = self;
    _leftTableView.separatorColor = [UIColor clearColor];
    _leftTableView.tableHeaderView = [UIView new];
    _leftTableView.tableFooterView = [UIView new];
    _leftTableView.estimatedRowHeight = 130.0f;
    _leftTableView.rowHeight = UITableViewAutomaticDimension;
    [_leftTableView registerNib:[UINib nibWithNibName:@"LeftTableViewCell1" bundle:nil] forCellReuseIdentifier:@"leftCell1"];
    [_leftTableView registerNib:[UINib nibWithNibName:@"knowStyleTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"knowledgeStyleTwo"];
 
    [_bgScrollView addSubview:_leftTableView];
    
    MJRefreshGifHeader *leftheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadleftTableViewNewData)];
    // 设置普通状态的动画图片
    [leftheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [leftheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [leftheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    _leftTableView.mj_header = leftheader;
    leftheader.lastUpdatedTimeLabel.hidden = YES;
    leftheader.stateLabel.hidden = YES;
    leftheader.ignoredScrollViewContentInsetTop = - 30;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(leftloadMoreData)];
    // 设置刷新图片
    [footer setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    _leftTableView.mj_footer = footer;
    
    
    _middleTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH, -35, WIDTH, _bgScrollView.frame.size.height - 555) style:UITableViewStyleGrouped];
    _middleTableView.delegate = self;
    _middleTableView.backgroundColor = RGBA(235, 234, 229, 1);
    _middleTableView.dataSource = self;
    _middleTableView.tableHeaderView = [UIView new];
    _middleTableView.tableFooterView = [UIView new];
    _middleTableView.estimatedRowHeight = 130.0f;
    _middleTableView.rowHeight = UITableViewAutomaticDimension;
    [_middleTableView registerNib:[UINib nibWithNibName:@"MiddleTableViewCell" bundle:nil] forCellReuseIdentifier:@"middleMessageID"];
    [_bgScrollView addSubview:_middleTableView];
    _middleTableView.separatorColor = [UIColor clearColor];
    
    MJRefreshGifHeader *middleheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadmiddleTableViewNewData)];
    // 设置普通状态的动画图片
    [middleheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [middleheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [middleheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    _middleTableView.mj_header = middleheader;
    //隐藏时间  和  状态
    middleheader.lastUpdatedTimeLabel.hidden = YES;
    middleheader.stateLabel.hidden = YES;
    middleheader.ignoredScrollViewContentInsetTop = - 30;
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *middleFooter = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(middleLoadMoreData)];
    // 设置刷新图片
    [middleFooter setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    _middleTableView.mj_footer = middleFooter;
    
    _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH * 2, -35, WIDTH, _bgScrollView.frame.size.height - 555) style:UITableViewStyleGrouped];
    _rightTableView.delegate = self;
    _rightTableView.backgroundColor = RGBA(235, 234, 229, 1);
    _rightTableView.dataSource = self;
    _rightTableView.tableHeaderView = [UIView new];
    _rightTableView.tableFooterView = [UIView new];
    _rightTableView.estimatedRowHeight = 130.0f;
    _rightTableView.rowHeight = UITableViewAutomaticDimension;
    [_bgScrollView addSubview:_rightTableView];
    
    [_rightTableView registerNib:[UINib nibWithNibName:@"ExpertStyleOneTableViewCell" bundle:nil] forCellReuseIdentifier:@"ExpertStyleOne"];
    [_rightTableView registerNib:[UINib nibWithNibName:@"ExpertStyleTwoTableViewCell" bundle:nil] forCellReuseIdentifier:@"ExpertStyleTwo"];
    _rightTableView.separatorColor = [UIColor clearColor];
    MJRefreshGifHeader *rightheader = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadrightTableViewNewData)];
    // 设置普通状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateIdle];
    // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [rightheader setImages:idleImages forState:MJRefreshStatePulling];
    // 设置正在刷新状态的动画图片
    [rightheader setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置header
    _rightTableView.mj_header = rightheader;
    rightheader.lastUpdatedTimeLabel.hidden = YES;
    rightheader.stateLabel.hidden = YES;
    rightheader.ignoredScrollViewContentInsetTop = - 30;
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    MJRefreshAutoGifFooter *rightFooter = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(rightloadMoreData)];
    // 设置刷新图片
    [rightFooter setImages:idleImages forState:MJRefreshStateRefreshing];
    // 设置尾部
    _rightTableView.mj_footer = rightFooter;
    
}
-(void)loadleftTableViewNewData
{
    [self getKnowledge];
    [_leftTableView reloadData];
    [_leftTableView.mj_header endRefreshing];
}
-(void)leftloadMoreData
{
    knowledgePage++;
    [self getKnowledge];
    [_leftTableView reloadData];
}

-(void)loadmiddleTableViewNewData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_middleTableView.mj_header endRefreshing];
        
    });
}
-(void)middleLoadMoreData
{
    
}

-(void)loadrightTableViewNewData
{
    [self getExpert];
    [_rightTableView reloadData];
    [_rightTableView.mj_header endRefreshing];
}
-(void)rightloadMoreData
{
    expertPage++;
    [self getExpert];
    [_rightTableView reloadData];
}

#pragma UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _leftTableView) {
       
        return knowledge.count;
    } else if(tableView == _middleTableView){
        //        return _middleArray.count;
        return 30;
    }else if(tableView == _rightTableView){
   
        return expert.count;
        
        
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        if (indexPath.row==1||indexPath.row==2||indexPath.row==5) {
            _leftTableView.rowHeight = 298;
            knowStyleTwoTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"knowledgeStyleTwo" forIndexPath:indexPath];
            cell.model = knowledge[indexPath.row];
            return cell;
        }
        else
        {
            _leftTableView.rowHeight = 153;
            LeftTableViewCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCell1" forIndexPath:indexPath];
            cell.model = knowledge[indexPath.row];
            
            return cell;
        }
        
    } else if(tableView == _middleTableView){
        MiddleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"middleMessageID" forIndexPath:indexPath];
        return cell;
    }
    else
    {
       if (indexPath.row==0)
       {
            _rightTableView.rowHeight = 227;
            ExpertStyleOneTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"ExpertStyleOne" forIndexPath:indexPath];
            cell.model = expert[indexPath.row];
            return cell;
       }
       else {
            _rightTableView.rowHeight = 203;
            ExpertStyleTwoTableViewCell*cell =[tableView dequeueReusableCellWithIdentifier:@"ExpertStyleTwo" forIndexPath:indexPath];
           cell.model = expert[indexPath.row];
           return cell;
        }
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_leftTableView) {
        NewsDetailViewController*VC = [[NewsDetailViewController alloc]init];
        knowledgeStyleOne *model = knowledge[indexPath.row];
        VC.url = model.contentUrl;
        [self.navigationController pushViewController:VC animated:YES];
    }
    else if (tableView==_middleTableView)
    {
        
    }
    else if (tableView==_rightTableView)
    {
        NewsDetailViewController*VC = [[NewsDetailViewController alloc]init];
        ExpertSearchModel *model = expert[indexPath.row];
        VC.url = model.aArticleUrl;
        [self.navigationController pushViewController:VC animated:YES];
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [searchTextField resignFirstResponder];

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [searchTextField resignFirstResponder];

    if (scrollView == _bgScrollView) {
        if (scrollView.contentOffset.x == 0) {
            [_segment selectedIndex:0];
        } else if (scrollView.contentOffset.x == WIDTH ) {
            [_segment selectedIndex:1];
        }else if (scrollView.contentOffset.x == WIDTH * 2 ) {
            [_segment selectedIndex:2];

        }
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(void)change
{
    
}


-(void)goBackPreviousPage{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark --UITextField Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{//搜索方法
    [searchTextField resignFirstResponder];
    return YES;
}

-(void)getKnowledge
{
    [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?keyWord=%@&page=%ld&type=knowledge",Search,[_searchStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],(long)knowledgePage] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        for (NSDictionary*myDict in responseObject[@"msg"]) {
            knowledgeStyleOne*model = [[knowledgeStyleOne alloc]init];
            [model yy_modelSetWithDictionary:myDict];
            [knowledge addObject:model];
            [_leftTableView.mj_footer endRefreshing];
            [_leftTableView reloadData];
            
        }
        
    } failure:^(NSString * _Nonnull errorLD) {
        knowledgePage--;
    }];
}

-(void)getExpert
{
    [GPAFNetworking3 get:[NSString stringWithFormat:@"%@?keyWord=%@&page=%ld&type=expert",Search,[_searchStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],(long)expertPage] progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull responseObject) {
        for (NSDictionary*myDict in responseObject[@"msg"]) {
            ExpertSearchModel* model = [[ExpertSearchModel alloc]init];
            [model yy_modelSetWithDictionary:myDict];
            [expert addObject:model];
            [_rightTableView.mj_footer endRefreshing];
            [_rightTableView reloadData];
            
        }
        
    } failure:^(NSString * _Nonnull errorLD) {
        expertPage--;
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
